import _ from "lodash";
export const messageHandler = (messages: Message[]) => {
  let result = _.cloneDeep(messages);
  let historyIndex = -1;
  let jailbreakIndex = -1;
  const history: Message[] = [];
  messages.forEach((e, i) => {
    if (e.type === "history") {
      historyIndex = i;
    }
    if (e.identifier === "jailbreak") {
      jailbreakIndex = i;
    }
    if (e.type === "chat") {
      history.push({ ...e, type: "preChat" });
    }
  });
  if (jailbreakIndex !== -1) {
    result.splice(jailbreakIndex, 0, messages.at(-1)!);
    result.pop();
  }
  if (historyIndex !== -1) {
    result.splice(historyIndex, 1, ...history);
    result = result.filter(
      (e) => !(history.some((f) => f.id === e.id) && e.type === "chat")
    );
  } else {
    result.push(...history);
  }
  return result;
};
